#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
#=============================================================================
#     FileName: db.py
#         Desc: To connect db and return a connection
#       Author: cold night
#        Email: wh_linux@126.com
#     HomePage: http://www.linuxzen.com/
#      Version: 0.0.1
#   LastChange: 2012-05-19 18:42:35
#      History:
#=============================================================================
'''

'''
    获取数据库
'''

from setting import DB_HOST, DB_PORT, DB_AUTH, DB_USER, DB_PASSWD, AUTH_DB, DB_NAME
from setting import DB_ENGINE


class MongoConnectError(Exception):
    '''
    定义自己的错误处理
    '''
    def __init__(self,value):
        self.value = value

    def __str__(self):
        return repr(self.value)

def get_db():
    '''
    连接数据库,并返回数据库
    '''
    if DB_ENGINE == 'mongo':
        from pymongo import Connection
        if DB_AUTH:
            connection = Connection(DB_HOST, DB_PORT)
            db = connection[AUTH_DB]
            result = db.authenticate(DB_USER, DB_PASSWD)
            if result:
                db = connection[DB_NAME]
                return db
            else:
                raise MongoConnectError("can not connection to mongodb,check your user and password")
        else:
            connection = Connection(DB_HOST, DB_PORT)
            return connection[DB_NAME]
    elif DB_ENGINE == 'mysql':
        import MySQLdb as mysqldb
        conn = mysqldb.Connection(host=DB_HOST, port=DB_PORT,
                      user=DB_USER, passwd=DB_PASSWD,
                      db=DB_NAME, charset='utf8')
        return conn
    else:
        raise ValueError("DB_ENGINE must be mysql/mongo in setting.py")        
